#coding:utf-8
from twisted.internet import protocol
import logging
import proxyclientfactory
import struct
import logging
import time
import proxyserver

CLIENT_STATE_INIT               = 0
CLIENT_STATE_LOGINED            = 1
CLIENT_STATE_TO_CLOSE           = 2

class Client(protocol.Protocol):
    def __init__(self, pid, addr):
        self.id = pid
        self.addr = addr
        self.ip = addr.host.decode('utf-8')
        self.serverConnect = None

    
    def dataReceived(self, data):
        if self.serverConnect:
            self.serverConnect.sendPacket(data)
        else:
            pass
    
    def connectionMade(self):
        logging.debug(u"connectionMade %d:%s",self.id,self.ip)
        self.serverConnect = proxyserver.ProxyServerSrv()
        self.serverConnect.setClient(self)
        self.serverConnect.start()

   
    def connectionLost(self, reason=protocol.connectionDone):
        logging.debug(u"connectionLost %d:%s",self.id,self.ip)
        self.serverConnect.stop()
        self.serverConnect.setClient(None)
        self.serverConnect = None
        proxyclientfactory.instance.removeProtocol(self)

    def sendPacket(self, pkt):
        self.transport.write(pkt)
        self.__lastactivetime = time.time()
        
    def abort(self):
        self.transport.abortConnection()

    def getId(self):
        return self.id

        
